package test.lucene.moreLikethis;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queries.mlt.MoreLikeThis;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import test.lucene.LuceneUtil;

public class App {
	
	public static void main(String[] args) {
		try {
			FSDirectory dir = LuceneUtil.init();
			DirectoryReader reader = DirectoryReader.open(dir);
			MoreLikeThis mlt = new MoreLikeThis(reader);
			
			mlt.setFieldNames(new String[]{"title", "text", "intro", "keywords"}); // 找“标题”和“作者”相似的  
			mlt.setAnalyzer(new IKAnalyzer(true));
//	        mlt.setMinTermFreq(1); // 默认值是2，建议自己做限制，否则可能查不出结果  
//	        mlt.setMinDocFreq(1); // 默认值是5，建议自己做限制，否则可能查不出结果  
			
			System.out.println(mlt);
			
			int docID = 105;
			
			Document doc = reader.document(docID); // 逐一过所有图书  
            System.out.println(doc.get("title"));  
            Query query = mlt.like(docID); // 准备相似搜索了  
            System.out.println(" query=" + query);  
            IndexSearcher searcher = new IndexSearcher(reader);
            TopDocs similarDocs = searcher.search(query, 10); // 开搜，做多10个结果  
            if (similarDocs.totalHits == 0)  
                System.out.println(" None like this"); // 只要结果不为空，就按这个打印出来  
            for (int i = 0; i < similarDocs.scoreDocs.length; i++) {  
                if (similarDocs.scoreDocs[i].doc != docID) { // 记着把自己排除掉哦  
                    doc = reader.document(similarDocs.scoreDocs[i].doc);  
                    System.out.println(" -> " + doc.getField("title").stringValue());  
                }  
            }
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
//		LuceneUtil.getTop10();
		
	}

}
